'use client'

import React, { useEffect, useMemo, useState } from 'react'
import { Card, CardHeader, CardTitle, CardContent } from './ui/card'
import { Button } from './ui/button'
import { Badge } from './ui/badge'
import { analyzeFast, adviseFast, AdvisorAllResult } from '@/lib/aiAdvisor'
import { Loader2 } from 'lucide-react'

interface AIAdvisorPanelProps {
  onClose?: () => void
}

const StatusBadge: React.FC<{ status?: string }> = ({ status }) => {
  const color = status === 'excellent' ? 'bg-emerald-100 text-emerald-700' : status === 'good' ? 'bg-blue-100 text-blue-700' : status === 'warning' ? 'bg-amber-100 text-amber-700' : 'bg-gray-100 text-gray-700'
  return <span className={`text-xs px-2 py-0.5 rounded ${color}`}>{status || 'normal'}</span>
}

const AIAdvisorPanel: React.FC<AIAdvisorPanelProps> = ({ onClose }) => {
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<AdvisorAllResult | null>(null)

  const localInsight = useMemo(() => analyzeFast(), [])

  useEffect(() => {
    let aborted = false
    const controller = new AbortController()
    setLoading(true)
    adviseFast(undefined, controller.signal).then(res => {
      if (!aborted) setResult(res)
    }).finally(() => {
      if (!aborted) setLoading(false)
    })
    return () => { aborted = true; controller.abort() }
  }, [])

  const kpis = result?.kpis || localInsight.kpis
  const bottlenecks = result?.bottlenecks || localInsight.bottlenecks
  const quickActions = result?.quickActions || localInsight.quickActions
  const plans = result?.plans

  return (
    <div className="fixed right-4 bottom-20 w-[420px] max-h-[70vh] overflow-auto z-[10000]">
      <Card className="shadow-2xl border border-white/20 bg-white/95 backdrop-blur-md">
        <CardHeader className="flex items-center justify-between flex-row">
          <CardTitle className="text-base">AI运营分析与方案</CardTitle>
          <div className="flex items-center gap-2">
            {loading && <Loader2 className="w-4 h-4 animate-spin" />}
            <Button size="sm" variant="outline" onClick={onClose}>关闭</Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <section>
            <div className="text-sm font-medium mb-2">关键指标</div>
            <div className="space-y-2">
              {kpis.slice(0, 6).map(k => (
                <div key={k.key} className="flex items-center justify-between text-sm">
                  <div className="text-gray-600">{k.key}</div>
                  <div className="flex items-center gap-2">
                    <div className="font-medium">{k.value}</div>
                    <StatusBadge status={k.status} />
                  </div>
                </div>
              ))}
            </div>
          </section>

          {bottlenecks.length > 0 && (
            <section>
              <div className="text-sm font-medium mb-2">可能瓶颈</div>
              <ul className="list-disc list-inside space-y-1 text-sm text-gray-700">
                {bottlenecks.map((b, i) => <li key={i}>{b}</li>)}
              </ul>
            </section>
          )}

          {quickActions.length > 0 && (
            <section>
              <div className="text-sm font-medium mb-2">立即行动建议</div>
              <ul className="list-disc list-inside space-y-1 text-sm text-gray-700">
                {quickActions.map((a, i) => <li key={i}>{a}</li>)}
              </ul>
            </section>
          )}

          {plans && plans.plans?.length > 0 && (
            <section>
              <div className="text-sm font-medium mb-2">优化方案（来自服务端）</div>
              <div className="space-y-2">
                {plans.plans.map(p => (
                  <div key={p.id} className={`p-2 rounded border ${plans.recommend === p.id ? 'border-emerald-400 bg-emerald-50' : 'border-gray-200'}`}>
                    <div className="flex items-center justify-between text-sm">
                      <div>方案 {p.id}</div>
                      {plans.recommend === p.id && <Badge>推荐</Badge>}
                    </div>
                    {p.kpis && (
                      <div className="text-xs mt-1 text-gray-600">{Object.entries(p.kpis).map(([k, v]) => `${k}:${v}`).join(' · ')}</div>
                    )}
                  </div>
                ))}
              </div>
            </section>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

export default AIAdvisorPanel

